package mil.af.amc.adpetracker.web.helpers;

import mil.af.amc.adpetracker.model.Account;
import mil.af.amc.adpetracker.model.Authority;
import mil.af.amc.adpetracker.service.AccountService;
import mil.af.amc.adpetracker.service.AuthorityService;
import mil.af.amc.radtaglibrary.tags.PageContextAwareBean;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.jsp.PageContext;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * View Helper for Authority Objects
 *
 * @author TSgt Jason Ferguson
 */
@Service("authorityViewHelper")
public class AuthorityViewHelper implements PageContextAwareBean {

    private PageContext pageContext;

    @Autowired
    public void setPageContext(PageContext pageContext) {
        this.pageContext = pageContext;
    }

    public AuthorityService authorityService;

    @Autowired
    public void setAuthorityService(AuthorityService authorityService) {
        this.authorityService = authorityService;
    }

    public AccountService accountService;

    @Autowired
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public List<Authority> getAll() {

        List<Authority> results = authorityService.getAll();
        Collections.sort(results);
        return results;

    }

    public Map getAuthorityIdMap() {

        ServletRequest request = pageContext.getRequest();
        int accountId = Integer.parseInt(request.getParameter("accountId"));

        Account acct = accountService.getById(accountId);

        Map authorityMap = new HashMap<Integer, String>();
        for (Authority a: acct.getAccountAuthorities()) {
            authorityMap.put(a.getId(), a.getAuthority());
        }

        return authorityMap;
    }

    public Integer[] getAuthorityIds() {

        ServletRequest request = pageContext.getRequest();
        int accountId = Integer.parseInt(request.getParameter("accountId"));

        Account acct = accountService.getById(accountId);
        Authority[] authorityArray = acct.getAccountAuthorities().toArray(new Authority[acct.getAccountAuthorities().size()]);

        Integer[] authorityIds = new Integer[authorityArray.length];
        for (int i = 0; i < authorityArray.length; i++) {
            authorityIds[i] = authorityArray[i].getId();
        }

        return authorityIds;
    }
}
